#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>

#define MAX_QUESTIONS 100
#define MAX_OPTIONS 4
#define BUFFER_SIZE 1024
#define MAX_USERS 100
#define MAX_USERNAME 50
#define MAX_PASSWORD 50
#define MAX_EXAMS 100
#define MAX_STUDENTS 50

// 试题结构体
typedef struct {
int exam_duration; // 考试时长（分钟）
int update_interval; // 题库更新周期（天）
} SystemConfig;

SystemConfig system_config = {120, 7}; // 默认考试时长 120 分钟，更新周期 7 天


typedef struct {
char username[MAX_USERNAME];
char password[MAX_PASSWORD];
char role[10]; // "admin" 或 "student"
} User;

User users[MAX_USERS];
char current_user[MAX_USERNAME]; // 记录当前登录用户
char current_role[10]; // 记录当前用户角色

#define MAX_OPTIONS 4
#define MAX_QUESTIONS 100

typedef struct {
    char type;       // 题型：'C' 选择题, 'J' 判断题, 'S' 主观题
    char question[256];
    char options[4][50];  // 仅选择题使用
    char answer[50];
} Question;

Question choice_questions[MAX_QUESTIONS];  // 选择题单独存储
int choice_count = 0;
Question judge_questions[MAX_QUESTIONS];   // 判断题单独存储
int judge_count = 0; 
Question subjective_questions[MAX_QUESTIONS]; // 主观题单独存储
int subjective_count = 0;

// 判断是否超过考试时间（单位：秒）
int has_time_exceeded(time_t start_time) {
int exam_duration = system_config.exam_duration * 60; // 转换为秒
time_t current_time = time(NULL);

return (difftime(current_time, start_time) >= exam_duration);
}

typedef struct {
char name[100]; // 考试名称
char date[20]; // 考试时间
char mode[50]; // 考试方式（如 "线上" 或 "线下"）
char exam_paper[100]; // 试卷名称
char students[MAX_STUDENTS][50]; // 考生名单
int student_count; // 考生人数
time_t start_time; // 考试开始时间
time_t end_time; // 考试结束时间
} Exam;

Exam exams[MAX_EXAMS];
int exam_count = 0;

// 全局变量
Question question_bank[MAX_QUESTIONS];
int question_count = 0;
Question exam_questions[MAX_QUESTIONS];
int exam_question_count = 0;
User users[MAX_USERS];
int user_count = 0;
char current_user[MAX_USERNAME]; // 记录当前登录用户
char choice;

void manage_question_bank();
void add_question();



// 保存用户数据
void save_users() {
FILE *file = fopen("users.txt", "w");
if (!file) {
perror("无法保存用户数据");
return;
}
for (int i = 0; i < user_count; i++) {
fprintf(file, "%s %s\n", users[i].username, users[i].password);
}
fclose(file);
}

// 去除字符串两端的引号
void trim_quotes(char *str) {
    size_t len = strlen(str);
    if (len > 1 && str[0] == '"' && str[len - 1] == '"') {
        memmove(str, str + 1, len - 2);
        str[len - 2] = '\0';
    }
}

void manage_users() {
if (strcmp(current_user, "manager") != 0) {
printf("无权限访问！\n");
return;
}

int choice;
while (1) {
printf("\n===== 用户管理 =====\n");
printf("1. 查看所有用户\n");
printf("2. 修改用户密码\n");
printf("3. 删除用户账号\n");
printf("4. 返回\n");
printf("请选择操作: ");
scanf("%d", &choice);

if (choice == 1) {
// **查看所有用户**
printf("\n===== 用户列表 =====\n");
for (int i = 0; i < user_count; i++) {
printf("用户名: %s\n", users[i].username);
}
}
else if (choice == 2) {
// **修改用户密码**
char username[MAX_USERNAME], new_password[MAX_PASSWORD];
printf("请输入要修改密码的用户名: ");
scanf("%s", username);

// **检查用户是否存在**
int found = -1;
for (int i = 0; i < user_count; i++) {
if (strcmp(users[i].username, username) == 0) {
found = i;
break;
}
}

if (found == -1) {
printf("用户不存在！\n");
} else {
printf("请输入新密码: ");
scanf("%s", new_password);
strcpy(users[found].password, new_password);
save_users();
printf("用户 %s 的密码已更新！\n", username);
}
}
else if (choice == 3) {
// **删除用户账号**
char username[MAX_USERNAME];
printf("请输入要删除的用户名: ");
scanf("%s", username);

// **管理员不能删除自己**
if (strcmp(username, "manager") == 0) {
printf("无法删除管理员账号！\n");
continue;
}

// **查找并删除用户**
int found = -1;
for (int i = 0; i < user_count; i++) {
if (strcmp(users[i].username, username) == 0) {
found = i;
break;
}
}

if (found == -1) {
printf("用户不存在！\n");
} else {
// **删除用户，数组前移**
for (int i = found; i < user_count - 1; i++) {
users[i] = users[i + 1];
}
user_count--;
save_users();
printf("用户 %s 已删除！\n", username);
}
}
else if (choice == 4) {
return; // **返回主菜单**
}
else {
printf("无效选择！\n");
}
}
}


// **题库管理模块** - 从 CSV 文件导入试题
void import_questions_from_csv(const char *filename) {
    FILE *file = fopen(filename, "r");
    if (!file) {
        perror("无法打开文件");
        return;
    }

    char buffer[BUFFER_SIZE];

    while (fgets(buffer, BUFFER_SIZE, file)) {
        if (question_count >= MAX_QUESTIONS) {
            printf("题库已满，无法导入更多题目。\n");
            break;
        }

        Question q;
        memset(&q, 0, sizeof(Question)); // 清空结构体

        // 读取题型
        char *token = strtok(buffer, ",");
        if (!token) continue; // 避免 token 为 NULL
        q.type = toupper(token[0]);

        // 读取题目内容
        token = strtok(NULL, ",");
        if (!token) continue; // 避免 token 为 NULL

        // **去除题号（例如 "26."）**
        char *dot_pos = strchr(token, '.'); // 找到题号后的 '.'
        if (dot_pos) {
            token = dot_pos + 1; // 跳过 "."
            while (*token == ' ') token++; // 去掉开头空格
        }
        strncpy(q.question, token, sizeof(q.question) - 1);
        trim_quotes(q.question);

        // 处理选择题
        if (q.type == 'C') {
            for (int i = 0; i < MAX_OPTIONS; i++) {
                token = strtok(NULL, ",");
                if (token) {
                    strncpy(q.options[i], token, sizeof(q.options[i]) - 1);
                    trim_quotes(q.options[i]);
                } else {
                    q.options[i][0] = '\0'; // 选项为空
                }
            }

            // 读取正确答案（选项 A-D）
            token = strtok(NULL, ",");
            if (token) {
                q.answer[0] = toupper(token[0]); // 只存储第一个字符
                q.answer[1] = '\0'; // 确保是字符串
            }

        } else if (q.type == 'J') { // 判断题（仅 T/F）
            token = strtok(NULL, ",");
            if (token) {
                q.answer[0] = toupper(token[0]); // 只存储第一个字符
                q.answer[1] = '\0';
            }
        } else if (q.type == 'S') { // 主观题（无标准答案）
            q.answer[0] = '\0'; // 主观题没有答案
        } else {
            continue;
        }

        // **将问题添加到题库**
        question_bank[question_count++] = q;
    }

    fclose(file);
}

void schedule_exam() {
int choice;

while (1) {
printf("\n===== 考试安排管理 =====\n");

if (exam_count == 0) {
printf("当前无考试记录。\n");
} else {
printf("已安排的考试：\n");
for (int i = 0; i < exam_count; i++) {
printf("%d. 考试名称: %s | 时间: %s | 方式: %s | 试卷: %s\n",
i + 1, exams[i].name, exams[i].date, exams[i].mode, exams[i].exam_paper);
}
}

printf("\n是否安排新考试？(1. 是 2. 否): ");
scanf("%d", &choice);
if (choice != 1) break;

if (exam_count >= MAX_EXAMS) {
printf("考试安排已满，无法安排更多考试！\n");
break;
}

Exam new_exam;
printf("请输入考试名称: ");
getchar();
fgets(new_exam.name, sizeof(new_exam.name), stdin);
new_exam.name[strcspn(new_exam.name, "\n")] = '\0';

printf("请输入考试日期（YYYY-MM-DD HH:MM）: ");
fgets(new_exam.date, sizeof(new_exam.date), stdin);
new_exam.date[strcspn(new_exam.date, "\n")] = '\0';

printf("请输入考试方式（线上/线下）: ");
fgets(new_exam.mode, sizeof(new_exam.mode), stdin);
new_exam.mode[strcspn(new_exam.mode, "\n")] = '\0';

printf("请输入考试时长（分钟）: ");
scanf("%d", &system_config.exam_duration);

printf("\n可用试卷列表：\n");
printf("1. exam_paper.txt\n");
printf("请选择试卷（输入文件名）: ");
getchar();
fgets(new_exam.exam_paper, sizeof(new_exam.exam_paper), stdin);
new_exam.exam_paper[strcspn(new_exam.exam_paper, "\n")] = '\0';

printf("请输入考生人数: ");
scanf("%d", &new_exam.student_count);
getchar();

for (int i = 0; i < new_exam.student_count; i++) {
printf("请输入第 %d 位考生姓名: ", i + 1);
fgets(new_exam.students[i], sizeof(new_exam.students[i]), stdin);
new_exam.students[i][strcspn(new_exam.students[i], "\n")] = '\0';
}

exams[exam_count++] = new_exam;
printf("\n考试安排完成！\n");
}
}

// **试卷生成模块** - 随机抽取试题
void generate_exam_paper(int num) {
    if (num > question_count) {
        printf("要求生成试卷的题目数超过了题库总题数！\n");
        return;
    }

    srand((unsigned)time(NULL));
    for (int i = question_count - 1; i > 0; i--) {
        int j = rand() % (i + 1);
        Question temp = question_bank[i];
        question_bank[i] = question_bank[j];
        question_bank[j] = temp;
    }

    FILE *fp = fopen("exam_paper.txt", "w");
    if (!fp) {
        perror("无法创建试卷文件");
        return;
    }

    fprintf(fp, "试卷生成：共 %d 道题\n\n", num);

    for (int i = 0; i < num; i++) {
        // 添加题型前缀
        if (question_bank[i].type == 'C') {
            fprintf(fp, "【选择】第 %d 题:\n%s\n", i + 1, question_bank[i].question);
        } else if (question_bank[i].type == 'J') {
            fprintf(fp, "【判断】第 %d 题:\n%s\n", i + 1, question_bank[i].question);
        } else if (question_bank[i].type == 'S') {
            fprintf(fp, "【主观】第 %d 题:\n%s\n", i + 1, question_bank[i].question);
        }

        // 修改后的选项输出（不显示A. B. C. D.前缀）
        if (question_bank[i].type == 'C') {  // 选择题
            for (int j = 0; j < MAX_OPTIONS; j++) {
                if (strlen(question_bank[i].options[j]) > 0) {
                    fprintf(fp, "%s\n", question_bank[i].options[j]);  // 直接输出选项内容
                }
            }
        } else if (question_bank[i].type == 'J') {  // 判断题
            fprintf(fp, "正确\n错误\n");  // 也可以简化为不显示T/F
        }

        fprintf(fp, "\n"); // 题目与下一题之间空行
    }

    fclose(fp);
}

// **用户管理模块** - 载入用户数据
void load_users() {
FILE *file = fopen("users.txt", "r");
if (!file) return;

while (fscanf(file, "%s %s", users[user_count].username, users[user_count].password) == 2) {
user_count++;
}
fclose(file);

// **检查是否存在管理员账号**
int has_admin = 0;
for (int i = 0; i < user_count; i++) {
if (strcmp(users[i].username, "manager") == 0) {
has_admin = 1;
break;
}
}

// **如果没有管理员，则创建默认管理员账号**
if (!has_admin && user_count < MAX_USERS) {
strcpy(users[user_count].username, "manager");
strcpy(users[user_count].password, "admin123"); // **默认密码**
user_count++;
save_users();
}
}

// 用户注册
void register_user() {
if (user_count >= MAX_USERS) {
printf("用户数已达上限！\n");
return;
}

char username[MAX_USERNAME], password[MAX_PASSWORD];
printf("请输入用户名: ");
scanf("%s", username);

// **禁止注册 "manager"**
if (strcmp(username, "manager") == 0) {
printf("无法注册该用户名！\n");
return;
}

printf("请输入密码: ");
scanf("%s", password);

// **防止重名**
for (int i = 0; i < user_count; i++) {
if (strcmp(users[i].username, username) == 0) {
printf("用户名已存在！\n");
return;
}
}

// **所有注册用户默认是学生**
strcpy(users[user_count].username, username);
strcpy(users[user_count].password, password);
user_count++;

save_users();
printf("注册成功！\n");
}

// 用户登录
int login() {
char username[MAX_USERNAME], password[MAX_PASSWORD];
printf("请输入用户名: ");
scanf("%s", username);
printf("请输入密码: ");
scanf("%s", password);

for (int i = 0; i < user_count; i++) {
if (strcmp(users[i].username, username) == 0 && strcmp(users[i].password, password) == 0) {
strcpy(current_user, username);

// **只有 "manager" 是管理员**
if (strcmp(username, "manager") == 0) {
strcpy(current_role, "admin");
} else {
strcpy(current_role, "student");
}

printf("登录成功，欢迎 %s！（角色：%s）\n", username, current_role);
return 1;
}
}

printf("用户名或密码错误！\n");
return 0;
}

// **考试管理模块** - 载入试卷
void load_exam_paper(const char *filename) {
    FILE *file = fopen(filename, "r");
    if (!file) {
        perror("无法打开试卷文件");
        return;
    }

    char buffer[BUFFER_SIZE];

    // **跳过第一行 "试卷生成："**
    fgets(buffer, BUFFER_SIZE, file);

    exam_question_count = 0;
    while (fgets(buffer, BUFFER_SIZE, file)) {
        // **判断题型**
        if (strncmp(buffer, "【选择】", 9) == 0) {
            exam_questions[exam_question_count].type = 'C';
        } else if (strncmp(buffer, "【判断】", 9) == 0) {
            exam_questions[exam_question_count].type = 'J';
        } else if (strncmp(buffer, "【主观】", 9) == 0) {
            exam_questions[exam_question_count].type = 'S';
        } else {
            continue; // 非题目行，跳过
        }

        // **读取题目**
        fgets(exam_questions[exam_question_count].question, sizeof(exam_questions[exam_question_count].question), file);

        // **根据题型读取选项**
        if (exam_questions[exam_question_count].type == 'C') {
            for (int i = 0; i < 4; i++) {
                fgets(exam_questions[exam_question_count].options[i], sizeof(exam_questions[exam_question_count].options[i]), file);
            }
        } else if (exam_questions[exam_question_count].type == 'J') {
            fgets(exam_questions[exam_question_count].options[0], sizeof(exam_questions[exam_question_count].options[0]), file); // "T. 正确"
            fgets(exam_questions[exam_question_count].options[1], sizeof(exam_questions[exam_question_count].options[1]), file); // "F. 错误"
        } else if (exam_questions[exam_question_count].type == 'S') {
            exam_questions[exam_question_count].options[0][0] = '\0'; // 主观题没有选项
        }

        exam_question_count++;
    }
    fclose(file);
}

// 保存成绩到文件
void save_score(const char *username, int score) {
    FILE *file = fopen("scores.txt", "a");
    if (!file) {
        perror("无法保存成绩");
        return;
    }
    fprintf(file, "%s %d\n", username, score); // 移除冗余字符
    fclose(file);
}

// 在线考试模块
void start_exam() {
    if (exam_question_count == 0) {
        printf("未找到试卷，请先生成试卷！\n");
        return;
    }

    int score = 0;
    char answer;

    // **记录考试开始时间**
    time_t start_time = time(NULL);

    printf("\n===== 在线考试开始 =====\n");
    for (int i = 0; i < exam_question_count; i++) {
        printf("\n第 %d 题: %s\n", i + 1, exam_questions[i].question);

        // **根据题型显示不同内容**
        if (exam_questions[i].type == 'C') {  // 选择题
            for (int j = 0; j < MAX_OPTIONS; j++) {
                if (strlen(exam_questions[i].options[j]) > 0) {
                    printf(" %c. %s\n", 'A' + j, exam_questions[i].options[j]);
                }
            }
            printf("请输入你的答案 (A-D): ");
        } else if (exam_questions[i].type == 'J') {  // 判断题
            printf(" T. 正确 / F. 错误\n");
            printf("请输入你的答案 (T/F): ");
        } else if (exam_questions[i].type == 'S') {  // 主观题
            printf("此题为主观题，请作答后按回车继续。\n");
            while (getchar() != '\n');  // 清除缓冲区
            getchar();  // 等待用户按回车继续
            continue;  // 直接跳到下一题（主观题不计分）
        }

        // **清除缓冲区，获取用户答案**
        while ((getchar()) != '\n');   
        scanf(" %c", &answer);
        answer = toupper(answer);

        // **检查答案有效性**
        if ((exam_questions[i].type == 'C' && (answer < 'A' || answer > 'D')) ||
            (exam_questions[i].type == 'J' && (answer != 'T' && answer != 'F'))) {
            printf("无效输入，请重新输入。\n");
            i--;  // 重新答题
            continue;
        }

        // **计算成绩**
        if (exam_questions[i].type == 'C' || exam_questions[i].type == 'J') {
            if (answer == exam_questions[i].answer[0]) {  // 只比较答案的第一个字符
                score += 10;
            }
        } else if (exam_questions[i].type == 'S') {
            // 主观题不计分，可能需要人工评分
        }

        // **检查是否超时**
        if (has_time_exceeded(start_time)) {
            printf("\n考试时间已到，系统自动提交试卷。\n");
            break;
        }
    }

    // **记录考试结束时间**
    time_t end_time = time(NULL);

    // **保存成绩**
    save_score(current_user, score);

    printf("\n考试已提交！请前往‘查看成绩’菜单查看得分。\n");
}

// 查看成绩
void view_scores() {
    FILE *file = fopen("scores.txt", "r");
    if (!file) {
        perror("无法读取成绩");
        return;
    }

    char username[MAX_USERNAME];
    int score;
    int found = 0;

    printf("\n===== 查看成绩 =====\n");

    // 修改格式匹配，直接读取用户名和分数
    while (fscanf(file, "%s %d", username, &score) == 2) {
        // 学生只能查看自己的成绩
        if (strcmp(current_role, "student") == 0 && strcmp(username, current_user) == 0) {
            printf("您的考试成绩：%d 分\n", score);
            found = 1;
            break;
        }
        // 管理员查看所有
        if (strcmp(current_role, "admin") == 0) {
            printf("用户: %s | 分数: %d 分\n", username, score);
            found = 1;
        }
    }

    fclose(file);

    if (!found) {
        printf("当前没有您的成绩记录！\n");
    }
}

// 成绩结构体
typedef struct {
    char username[MAX_USERNAME];
    int score;
} Score;

Score scores[MAX_USERS]; // 存储所有用户的成绩
int score_count = 0;      // 记录成绩数量

// 加载成绩数据
void load_scores() {
    FILE *file = fopen("scores.txt", "r");
    if (!file) return;

    while (fscanf(file, "%s %d", scores[score_count].username, &scores[score_count].score) == 2) {
        score_count++;
    }
    fclose(file);
}

// 计算平均分
float calculate_average_score() {
    if (score_count == 0) return 0.0;

    int total = 0;
    for (int i = 0; i < score_count; i++) {
        total += scores[i].score;
    }
    return (float)total / score_count;
}

// 计算最高分
int calculate_max_score() {
    if (score_count == 0) return 0;

    int max_score = scores[0].score;
    for (int i = 1; i < score_count; i++) {
        if (scores[i].score > max_score) {
            max_score = scores[i].score;
        }
    }
    return max_score;
}

// 计算最低分
int calculate_min_score() {
    if (score_count == 0) return 0;

    int min_score = scores[0].score;
    for (int i = 1; i < score_count; i++) {
        if (scores[i].score < min_score) {
            min_score = scores[i].score;
        }
    }
    return min_score;
}

// 计算及格率
float calculate_pass_rate(int pass_score) {
    if (score_count == 0) return 0.0;

    int pass_count = 0;
    for (int i = 0; i < score_count; i++) {
        if (scores[i].score >= pass_score) {
            pass_count++;
        }
    }
    return (float)pass_count / score_count * 100;
}

// 显示成绩分析
void show_score_analysis() {
    load_scores();

    if (score_count == 0) {
        printf("暂无成绩数据！\n");
        return;
    }

    printf("\n===== 成绩分析 =====\n");
    printf("平均分: %.2f\n", calculate_average_score());
    printf("最高分: %d\n", calculate_max_score());
    printf("最低分: %d\n", calculate_min_score());
    printf("及格率: %.2f%%\n", calculate_pass_rate(60)); // 假设及格分为60
}

// 保存系统配置
void save_system_config() {
    FILE *file = fopen("system_config.txt", "w");
    if (!file) {
        perror("无法保存系统配置");
        return;
    }
    fprintf(file, "%d %d\n", system_config.exam_duration, system_config.update_interval);
    fclose(file);
}

// 加载系统配置
void load_system_config() {
    FILE *file = fopen("system_config.txt", "r");
    if (!file) return;

    fscanf(file, "%d %d", &system_config.exam_duration, &system_config.update_interval);
    fclose(file);
}

// 显示系统配置
void show_system_config() {
    printf("\n===== 系统配置 =====\n");
    printf("考试时长: %d 分钟\n", system_config.exam_duration);
    printf("题库更新周期: %d 天\n", system_config.update_interval);
}

// 修改系统配置
void update_system_config() {
    printf("请输入新的考试时长（分钟）: ");
    scanf("%d", &system_config.exam_duration);
    printf("请输入新的题库更新周期（天）: ");
    scanf("%d", &system_config.update_interval);
    save_system_config();
    printf("系统配置已更新！\n");
}

// 日志记录
void log_event(const char *event) {
    FILE *file = fopen("system_log.txt", "a");
    if (!file) {
        perror("无法记录日志");
        return;
    }
    fprintf(file, "[%s] %s\n", __DATE__, event);
    fclose(file);
}

// 数据备份
void backup_data() {
    // 备份用户数据
    system("cp users.txt users_backup.txt");
    // 备份成绩数据
    system("cp scores.txt scores_backup.txt");
    // 备份系统配置
    system("cp system_config.txt system_config_backup.txt");
    log_event("数据备份完成");
    printf("数据备份成功！\n");
}

// 数据恢复
void restore_data() {
    // 恢复用户数据
    system("cp users_backup.txt users.txt");
    // 恢复成绩数据
    system("cp scores_backup.txt scores.txt");
    // 恢复系统配置
    system("cp system_config_backup.txt system_config.txt");
    log_event("数据恢复完成");
    printf("数据恢复成功！\n");
}

// 系统管理子菜单
void system_management_menu() {
    int choice;
    while (1) {
        printf("\n===== 系统管理 =====\n");
        printf("1. 查看系统配置\n");
        printf("2. 修改系统配置\n");
        printf("3. 数据备份\n");
        printf("4. 数据恢复\n");
        printf("5. 返回主菜单\n");
        printf("请选择操作: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                show_system_config();
                break;
            case 2:
                update_system_config();
                break;
            case 3:
                backup_data();
                break;
            case 4:
                restore_data();
                break;
            case 5:
                return;
            default:
                printf("无效选择！\n");
        }
    }
}

void manage_question_bank() {
    int choice;

    while (1) {
        printf("\n===== 题库管理 =====\n");

        // **显示当前题库内容**
        if (question_count == 0) {
            printf("暂无试题记录。\n");
        } else {
            printf("当前题库共有 %d 道试题：\n", question_count);
            for (int i = 0; i < question_count; i++) {
                printf("%d. [%c] %s\n", i + 1, question_bank[i].type, question_bank[i].question);
            }
        }

        printf("\n请选择操作：\n");
        printf("1. 手动添加试题\n");
        printf("2. 从 CSV 文件更新试题\n");
        printf("3. 返回主菜单\n");
        printf("请输入选择: ");
        scanf("%d", &choice);

        if (choice == 1) {
            // **手动添加试题**
            if (question_count >= MAX_QUESTIONS) {
                printf("题库已满，无法添加更多试题！\n");
                continue;
            }

            Question new_question;
            getchar(); // 清除缓冲区
            printf("请选择题型 (C-选择题, J-判断题, S-主观题): ");
            scanf("%c", &new_question.type);
            new_question.type = toupper(new_question.type);
            getchar(); // 清除缓冲区

            printf("请输入试题内容: ");
            fgets(new_question.question, sizeof(new_question.question), stdin);
            new_question.question[strcspn(new_question.question, "\n")] = '\0'; // 去除换行符

            if (new_question.type == 'C') {
                printf("请输入 4 个选项:\n");
                for (int i = 0; i < 4; i++) {
                    printf("选项 %c: ", 'A' + i);
                    fgets(new_question.options[i], sizeof(new_question.options[i]), stdin);
                    new_question.options[i][strcspn(new_question.options[i], "\n")] = '\0';
                }
            
                printf("请输入正确答案 (A-D): ");
                char correct_option;
                scanf(" %c", &correct_option);
                correct_option = toupper(correct_option);
            
                // 存入 answer 数组
                new_question.answer[0] = correct_option;
                new_question.answer[1] = '\0';  // 确保字符串结束
            } 
            else if (new_question.type == 'J') {
                strcpy(new_question.options[0], "T. 正确");
                strcpy(new_question.options[1], "F. 错误");
                new_question.options[2][0] = '\0';
                new_question.options[3][0] = '\0';
            
                printf("请输入正确答案 (T/F): ");
                char correct_option;
                scanf(" %c", &correct_option);
                correct_option = toupper(correct_option);
            
                // 存入 answer 数组
                new_question.answer[0] = correct_option;
                new_question.answer[1] = '\0';  // 确保字符串结束
            } 
            else if (new_question.type == 'S') {
                new_question.options[0][0] = '\0';
                new_question.answer[0] = '\0';  // 主观题无正确答案
            } 
            else {
                printf("无效题型，请重新输入。\n");
                return;  // 退出当前操作
            }

            // **检查试题是否已存在**
            int exists = 0;
            for (int i = 0; i < question_count; i++) {
                if (strcmp(question_bank[i].question, new_question.question) == 0) {
                    exists = 1;
                    break;
                }
            }

            if (exists) {
                printf("该试题已存在，无法添加。\n");
            } else {
                question_bank[question_count++] = new_question;
                printf("试题添加成功！\n");
            }
        } 
        else if (choice == 2) {
            // **从 CSV 文件更新试题**
            import_questions_from_csv("question.csv");
        } 
        else if (choice == 3) {
            return; // 返回主菜单
        } 
        else {
            printf("无效选择，请重新输入。\n");
        }
    }
}

void menu() {
int choice;
while (1) {
printf("\n===== 考试系统 =====\n");
printf("1. 用户注册\n");
printf("2. 用户登录\n");
printf("3. 退出\n");

// **学生和管理员都能访问**
if (strcmp(current_role, "student") == 0 || strcmp(current_role, "admin") == 0) {
printf("4. 开始考试\n");
printf("5. 查看成绩\n");
}

// **只有管理员 "manager" 能访问**
if (strcmp(current_role, "admin") == 0) {
printf("6. 成绩分析\n");
printf("7. 系统管理\n");
printf("8. 题库管理\n");
printf("9. 考试安排管理\n");
printf("10. 用户管理（仅管理员）\n"); // **新增功能**
}

printf("请选择操作: ");
scanf("%d", &choice);

switch (choice) {
case 1:
register_user();
break;
case 2:
if (login()) {
load_exam_paper("exam_paper.txt");
}
break;
case 3:
printf("退出系统。\n");
return;
case 4:
if (strlen(current_user) > 0) {
start_exam();
} else {
printf("请先登录！\n");
}
break;
case 5:
if (strlen(current_user) > 0) {
view_scores();
} else {
printf("请先登录！\n");
}
break;
case 6:
if (strcmp(current_role, "admin") == 0) {
show_score_analysis();
} else {
printf("无权限访问！\n");
}
break;
case 7:
if (strcmp(current_role, "admin") == 0) {
system_management_menu();
} else {
printf("无权限访问！\n");
}
break;
case 8:
if (strcmp(current_role, "admin") == 0) {
manage_question_bank();
} else {
printf("无权限访问！\n");
}
break;
case 9:
if (strcmp(current_role, "admin") == 0) {
schedule_exam();
} else {
printf("无权限访问！\n");
}
break;
case 10:
if (strcmp(current_role, "admin") == 0) {
manage_users();
} else {
printf("无权限访问！\n");
}
break;
default:
printf("无效选择！\n");
}
}
}

// **主函数**
int main() {
    load_users();
    import_questions_from_csv("question.csv");
    generate_exam_paper(10);
    load_exam_paper("exam_paper.txt");
    menu();
    return 0;
}